#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
# Version v2.0
set -e

# Generic macro defintions.
OS_INFO=$(cat /etc/*release|head -n 1)
MYSQL_BASE_DIR="$(cd "`dirname "$0"`"/..; pwd)"
cd $MYSQL_BASE_DIR
MYSQL_VERSION="$(echo $(bin/mysqld --version|awk -F mysqld '{print $2}'|awk -F '(' '{print $1}'))"
MYSQL_USER="wl4g_mysql"
MYSQL_GROUP="wl4g_mysql"
MYSQL_DATA_DIR="${MYSQL_BASE_DIR}/data/"
MYSQL_PLUGIN_DIR="${MYSQL_BASE_DIR}/lib/plugin/"
MYSQL_CONF_FILE="${MYSQL_BASE_DIR}/conf/my.cnf"
MYSQL_LOG_ERR="${MYSQL_BASE_DIR}/log/mysqld-${MYSQL_USER}.err"
MYSQL_LOG_BIN="${MYSQL_DATA_DIR}/mysqld-${MYSQL_USER}-logbin"
MYSQL_PID_FILE="${MYSQL_BASE_DIR}/run/mysqld-${MYSQL_USER}.pid"
MYSQL_SOCKET="${MYSQL_BASE_DIR}/run/mysqld-${MYSQL_USER}.sock"

if [ "$USER" != "root" ]; then
  echo "Use the root user to execution this script!"
  exit 2
fi

#
# Load user and system environments.
#
# [Note]: 1, Using $() has the same effect as `` double backslash, but the latter is more compatible in the UNIX kernel.
# {Note}: 2, When use set -e, when source /etc/profile is executed in centos6.xx, the process is interrupted. Only use `` backslash to run normal!
#

if [ -f "/etc/profile" ]; then # e.g. CentOS.x, Ubuntu.x
  `source /etc/profile`
fi
if [ -f "/etc/bashrc" ]; then # e.g. CentOS.x
  `source /etc/bashrc`
fi
if [ -f "/etc/bash.bashrc" ]; then # e.g. Ubuntu.x
  `source /etc/bash.bashrc`
fi
if [ -f "~/.bashrc" ]; then # e.g. CentOS.x, Ubuntu.x
  `source ~/.bashrc`
fi
if [ -f "~/.bash_profile" ]; then # e.g. CentOS.x
  `source ~/.bash_profile`
fi
if [ -f "~/.profile" ]; then # e.g. Ubuntu.x
  `source ~/.profile`
fi


#
# Get already running mysqld pids.
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
function getMysqldPids(){
  PIDS=$(ps -ef|grep ${MYSQL_BASE_DIR}|grep mysqld|grep -v grep|cut -c 9-15)
  echo $PIDS
  return 0
}


#
# Pre init of required directory and permission etc.
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function preInitInstall() {
  if [[ "$MYSQL_GROUP" != "root" && -z "$(grep "^$MYSQL_GROUP" /etc/group)" ]]; then
    groupadd $MYSQL_GROUP
  fi
  if [[ "$MYSQL_USER" != "root" && -z "$(grep "^$MYSQL_USER" /etc/passwd)" ]]; then
    useradd -g $MYSQL_GROUP $MYSQL_USER
  fi
  mkdir -p ${MYSQL_BASE_DIR}/data
  mkdir -p ${MYSQL_BASE_DIR}/conf
  mkdir -p ${MYSQL_BASE_DIR}/log
  mkdir -p ${MYSQL_BASE_DIR}/run
  # Grant access.
  chmod -R 755 ${MYSQL_BASE_DIR} && chown -R ${MYSQL_USER}:${MYSQL_GROUP} ${MYSQL_BASE_DIR}
}


#
# Initializing config of my.cnf
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInitConfiguration() {
cat<<EOF>${MYSQL_CONF_FILE}
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# For more setup recommendations or green installation guidelines,
# @see http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
port = 3306
# Configured at install time. See: script/mysqld_install.sh
#basedir = {MYSQL_HOME}
#datadir = {basedir}/data
#socket = {basedir}/run/mysqld-{MYSQL_USER}.sock
#pid-file = {basedir}/run/mysqld-{MYSQL_USER}.pid
#log-error = {basedir}/log/mysqld-{MYSQL_USER}.err

# To turn on a very important data integrity option: logging changes to the binary log between backups.
#log_bin = {basedir}/data/mysqld-{MYSQL_USER}-log.bin
expire_logs_days = 15
# Warning: Unsigned value 2147483648 adjusted to 1073741824, max allowed set to 1G ??
max_binlog_size = 1G
server_id = 1

# Ignore SQL condition case.(1:ignore)
# Note: When mysql8+, after initialization, is is not allowed to change this setting.
# @see http://blog.itpub.net/20893244/viewspace-2565069/
# @see https://bugs.mysql.com/bug.php?id=90695
#lower_case_table_names = 1

# Set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
innodb_buffer_pool_size = 6144M
max_allowed_packet = 1024M
#slave_max_allowed_packet = 2048M
max_connections = 2500

# To set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
explicit_defaults_for_timestamp = true

# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links = 0

# Recommended in standard MySQL setup
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES


# @Deprecated of using script/mysqld_install.sh
# 
#[mysqld_safe]
# {datadir}/log/mysqld.log
#log-error = log/mysqld.log
# {datadir}/mysqld.pid
#pid-file = mysqld.pid
EOF
}


#
# Initializing mysqld data directory. 
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
# See: https://dev.mysql.com/doc/refman/5.7/en/data-directory-initialization.html#data-directory-initialization-server-actions
#
function doInitDBMetaData() {
  if [ ! -d "${MYSQL_DATA_DIR}/performance_schema" ]; then
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Initializing mysql datadir to '${MYSQL_DATA_DIR}', It may take about 10 ~ 60sec ......  "

    # Using --defaults-file=xx prevent loading exist default config: e.g. /etc/my.cnf
    INIT_CMD="${MYSQL_BASE_DIR}/bin/mysqld \
        --defaults-file=${MYSQL_CONF_FILE} \
  	--initialize \
  	--user=${MYSQL_USER} \
  	--basedir=${MYSQL_BASE_DIR} \
  	--datadir=${MYSQL_DATA_DIR} \
  	--plugin-dir=${MYSQL_PLUGIN_DIR}"
    `${INIT_CMD}`
  else
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Skip initialize mysqld metadata, because dir of '${MYSQL_BASE_DIR}' the catalog has data, is it initialized?"
    exit 2
  fi
}


#
# Install system service.  (/etc/systemd/system/mysqld.service   or   /lib/systemd/system/mysqld.service)
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInstallSystemdService(){
  SERVICE_D_FILE="/lib/systemd/system/mysqld.service"  # e.g. Ubuntu16.x-, CentOS7.x
  if [ -n "$(cat /etc/*release |grep NAME|grep 'Ubuntu 19')" ]; then  # Ubuntu16.x
    SERVICE_D_FILE="/etc/systemd/system/mysqld.service"
  fi
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Installing mysqld systemctl service ..."

  # Backing up older systemctl mysqld.service(if necessary).
  if [ -f "$SERVICE_D_FILE" ]; then
    BAK_SERVICE_D_FILE="${SERVICE_D_FILE}_"$(date +'%y%m%d%H%M%S')
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Backing up older install mysqld.service from '${SERVICE_D_FILE}' to '${BAK_SERVICE_D_FILE}"
    `mv ${SERVICE_D_FILE} ${BAK_SERVICE_D_FILE}`
  fi

cat<<EOF>$SERVICE_D_FILE
#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# Version v2.0
# MySQL ${MYSQL_VERSION} systemd service.

[Unit]
Description=MySQL ${MYSQL_VERSION} Server
After=network.target

[Install]
WantedBy=multi-user.target

[Service]
Type=fork
Environment=MYSQL_HOME="${MYSQL_BASE_DIR}"
User=${MYSQL_USER}
Group=${MYSQL_GROUP}
PIDFile=${MYSQL_PID_FILE}

ExecStart=/bin/sh -c "exec \${MYSQL_HOME}/bin/mysqld \\
--defaults-file=\${MYSQL_HOME}/conf/my.cnf \\
--basedir=\${MYSQL_HOME} \\
--datadir=${MYSQL_DATA_DIR} \\
--plugin-dir=${MYSQL_PLUGIN_DIR} \\
--user=${MYSQL_USER} \\
--log-error=${MYSQL_LOG_ERR} \\
--log_bin=${MYSQL_LOG_BIN} \\
--pid-file=${MYSQL_PID_FILE} \\
--socket=${MYSQL_SOCKET}"
#--skip-grant-tables

ExecReload=/bin/kill -s HUP \$MAINPID
StandardOutput=${MYSQL_BASE_DIR}/log/mysqld.out
StandardError=journal
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=5
TimeoutSec=600
Restart=always
PermissionsStartOnly=true
RuntimeDirectoryMode=755
PrivateTmp=false
EOF

    # Configure systemd service & startup.
    /bin/systemctl daemon-reload
    /bin/systemctl enable mysqld
    /bin/systemctl start mysqld
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Started $(getMysqldPids) on ${SERVICE_D_FILE}"
}


#
# Install init.d service.  (/etc/init.d/mysqld.service)
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInstallInitdService() {
  SERVICE_D_FILE="/etc/init.d/mysqld.service"
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Fallback install init.d service to ${SERVICE_D_FILE} ... , because current OS: '${OS_INFO}' does not support systemctl dbus !"

  # Backing up older systemctl mysqld.service(if necessary).
  if [ -f "$SERVICE_D_FILE" ]; then
    BAK_SERVICE_D_FILE="${SERVICE_D_FILE}_"$(date +'%y%m%d%H%M%S')
    echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [WARN] Backing up older install mysqld.service from '${SERVICE_D_FILE}' to '${BAK_SERVICE_D_FILE}"
    `mv ${SERVICE_D_FILE} ${BAK_SERVICE_D_FILE}`
  fi

cat<<EOF>$SERVICE_D_FILE
#!/bin/bash
# Copyright (c) 2017 ~ 2025, the original author wangl.sir individual Inc,
# All rights reserved. Contact us wanglsir<wangl@gmail.com, 983708408@qq.com>
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @ad. https://github.com/wl4g/super-devops or https://gitee.com/wl4g/super-devops
# @see https://yq.aliyun.com/articles/741365
# @see https://www.jianshu.com/p/f6437e914584
# @see https://wang4ever.lofter.com/post/1cca927e_1c752cc99
#
# Version v2.0
set -e

MYSQL_HOME=${MYSQL_BASE_DIR}
# Get the execution command arg1.
COMMAND=\$1

# Start function.
function start(){
  PIDS=\$(getPids) # Get current process code.
  if [ -z "\$PIDS" ]; then
    # When mysqld_safe starts mysqld, it does not auto create log.err
    touch ${MYSQL_LOG_ERR} && chown -R ${MYSQL_USER}:${MYSQL_GROUP} ${MYSQL_LOG_ERR}

    EXEC_CMD="\${MYSQL_HOME}/bin/mysqld_safe \\
	--defaults-file=\${MYSQL_HOME}/conf/my.cnf \\
	--basedir=\${MYSQL_HOME} \\
	--datadir=${MYSQL_DATA_DIR} \\
	--plugin-dir=${MYSQL_PLUGIN_DIR} \\
	--user=${MYSQL_USER} \\
	--log-error=${MYSQL_LOG_ERR} \\
	--log_bin=${MYSQL_LOG_BIN} \\
	--pid-file=${MYSQL_PID_FILE} \\
	--socket=${MYSQL_SOCKET} \\
	--open-files-limit=102400"
	#--skip-grant-tables
    nohup \$EXEC_CMD > \${MYSQL_HOME}/log/mysqld.out 2>&1 < /dev/null &

    echo -n "MySQL ${MYSQL_VERSION} Server starting ..."
    while true
    do
      PIDS=\$(getPids)
      if [ "\$PIDS" == "" ]; then
        echo -n ".";
        sleep 0.8;
      else
        /bin/echo \$PIDS >"${MYSQL_PID_FILE}"
        break;
      fi
    done
    echo -e "\nStarted on "\$PIDS
  else
    echo "MySQL ${MYSQL_VERSION} Server is running "\$PIDS
  fi
}

# Stop function.
function stop(){
  PIDS=\$(getPids) # Get current process code.
  if [ -z "\$PIDS" ]; then
    echo "No mysqld running!"
  else
    echo -n "mysqld stopping by \$PIDS ..."
    kill -s TERM \$PIDS
    while true
    do
      PIDS=\$(getPids)
      if [ "\$PIDS" == "" ]; then
        /bin/rm -rf ${MYSQL_PID_FILE}
        break;
      else
        echo -n ".";
        sleep 0.8;
      fi
    done
    echo -e "\nStop Mysqld successfully."
  fi
}

# Status function.
function status(){
  ps -ef | grep mysqld | grep -v grep | grep -i ${MYSQL_BASE_DIR}
}

# Got pids.
function getPids(){
  PIDS=\$(ps ax | grep mysqld | grep -i ${MYSQL_BASE_DIR} | grep -v grep | awk '{print \$1}')
  echo \$PIDS # Output execution result value.
  return 0 # Return the execution result code.
}

# Executive operations.
case \$COMMAND in
  status)
    status
    ;;
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
    *)
  echo $"Usage:{start|stop|restart|status}"
  exit 2
esac
EOF

  #   # Configure init.d service & startup.
  chmod 755 $SERVICE_D_FILE && ${SERVICE_D_FILE} start
  echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] Started $(getMysqldPids) on ${SERVICE_D_FILE}"
}


#
# Install manager service.  (total)
# @author wanglsir<wangl@gmail.com, 983708408@qq.com>
#
function doInstallServiceAndStartup() {
  if [ -f "/bin/systemctl" ]; then  # Check sytemctl support?
    doInstallSystemdService
  else   # Using init.d service.
    doInstallInitdService
  fi
}


# Main green install.
preInitInstall
doInitConfiguration
doInitDBMetaData
doInstallServiceAndStartup

echo -e "=> $(date +'%y/%m/%d %H:%M:%S') [INFO] MySQL ${MYSQL_VERSION} server system service installed successfully! \
please using '${SERVICE_D_FILE}' to management it.\n"
